package com.njuse.jvmfinal.memory.jclass.runtimeConstantPool.constant.ref;

import com.njuse.jvmfinal.classloader.classfileparser.constantpool.info.FieldrefInfo;
import com.njuse.jvmfinal.memory.jclass.Field;
import com.njuse.jvmfinal.memory.jclass.JClass;
import com.njuse.jvmfinal.memory.jclass.runtimeConstantPool.RuntimeConstantPool;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class FieldRef extends MemberRef {
    private Field field;

    public FieldRef(RuntimeConstantPool runtimeConstantPool, FieldrefInfo fieldrefInfo) {
        super(runtimeConstantPool, fieldrefInfo);
      //  System.out.println(this.name+this.descriptor);
    }

    public Field findfield() {
    	JClass t=findclass();
    	return findfield(t);
    }
    
    public Field findfield(JClass clazz) {
    	
      Field[] fields=clazz.getFields();
      for (int i=0;i<fields.length;i++) {
    	  if (fields[i].getDescriptor().equals(descriptor) && fields[i].getName().equals(name)) {
    		  return fields[i];
    	  }
      }
      
      if (clazz.getSuperClass() != null) {
          Field temp=findfield(clazz.getSuperClass());
          if (temp!=null) return temp;
      } 
      
      JClass[] interfaces=clazz.getInterfaces();
      for (int i=0;i<interfaces.length;i++) {
          Field temp =findfield(interfaces[i]);
          if (temp!= null) return temp;
      } 
    	return null;
    }
}
